package fr.unice.progmobile.scratchpad;

import fr.unice.progmobile.scratchpad.data.Scratchpad;
import fr.unice.progmobile.scratchpad.db.ScratchpadOperations;
import fr.unice.progmobile.scratchpad.db.exceptions.ScratchpadNotFoundException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ConsulterActivity extends Activity {

	final String CURRENT_SCRATCHPAD = "current";
	
	private ScratchpadOperations sop;
	private int id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_consulter);
		
		Intent intent = getIntent();
		id = intent.getIntExtra(CURRENT_SCRATCHPAD, -1);
		
		sop = new ScratchpadOperations(this);
		sop.open();
		
		try {
			Scratchpad s = sop.getScratchpadWithId(id);
			TextView titre = (TextView) findViewById(R.id.textview_titre);
			titre.setText(s.getTitle());
			TextView description = (TextView) findViewById(R.id.textview_description);
			description.setText(s.getDescription());
			ImageView imageview = (ImageView) findViewById(R.id.imageview_image);
			imageview.setImageBitmap(s.getImage());
			Button modifier = (Button) findViewById(R.id.button_modifier);
			modifier.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ConsulterActivity.this, ModifierActivity.class);
					intent.putExtra(CURRENT_SCRATCHPAD, id);
					startActivity(intent);
				}		
			});
			Button supprimer = (Button) findViewById(R.id.button_supprimer);
			supprimer.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					SuppressDialog();
				}		
			});
		} catch (ScratchpadNotFoundException e) {
			Toast.makeText(getApplicationContext(), "Scratchpad invalide !", Toast.LENGTH_LONG).show();
		} finally {
			sop.close();
		}
	}
	
	@Override
	public void onBackPressed() {
		Intent intent = new Intent(ConsulterActivity.this, MainActivity.class);
		startActivity(intent);
		super.onBackPressed();
	}
	
	public void SuppressDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Voulez-vous supprimer ce scratchpad?");
		builder.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
				sop.open();
				sop.removeScratchpadWithID(id);
				sop.close();
				Intent intent = new Intent(ConsulterActivity.this, MainActivity.class);
				startActivity(intent);
		    }
		});
		builder.setNegativeButton("Non", null);
		builder.show();
	}
}
